<template>
  <a-modal
    v-model:open="openForm"
    width="60vw"
    :title="`支付宝${props.rowData.productName ? '-' + props.rowData.productName : ''}`"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form ref="formRef" :model="formData" v-bind="formOptions" :rules="props.formType == 'view' ? {} : rules" :disabled="props.formType == 'view'">
      <a-row :gutter="16">
        <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-400' }">基本信息</group-title>
        <a-col class="gutter-row" :span="24">
          <a-form-item label="商户号/支付宝账号:" :name="['jSubject', 'account']">
            <a-input v-model:value="jSubject.account" placeholder="请输入商户号/支付宝账号" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="姓名:" :name="['jSubject', 'name']">
            <a-input v-model:value="jSubject.name" placeholder="请输入姓名" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="手机号码:" :name="['jSubject', 'phone']">
            <a-input v-model:value="jSubject.phone" placeholder="请输入手机号码" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="邮箱:" :name="['jSubject', 'email']">
            <a-input v-model:value="jSubject.email" placeholder="请输入邮箱" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24"> <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-400' }">经营信息</group-title></a-col>
        <!-- <a-col class="gutter-row" :span="24">
          <a-form-item label="经营类目:" name="mccCode">
            <CustomSelect
              ref="qualificationRef"
              v-model:value="jSubject.mccCode"
              :placeholder="'请先选择经营类目'"
              :api="businessCategoryApi"
              :query-param-key="'categoryName'"
              value-field="categoryCode"
              label-field="categoryName"
            />
          </a-form-item>
        </a-col> -->
        <a-col class="gutter-row" :span="12">
          <a-form-item label="主体类型:" :name="['jSubject', 'subjectType']">
            <a-select v-model:value="jSubject.subjectType" :options="SUBJECT_TYPE" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="一级经营类目:" :name="['jSubject', 'mccCodeOne']">
            <CustomSelect
              v-model:value="jSubject.mccCodeOne"
              :placeholder="'请先选择营业主体'"
              @change="changeMccCodeOne"
              :api="apiSource.businessPage"
              :searchFlag="false"
              :queryParams="headParams"
              :initParams="headInitParams"
              value-field="categoryCode"
              label-field="categoryName"
            />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="二级经营类目:" :name="['jSubject', 'mccCodeTwo']">
            <CustomSelect
              v-model:value="jSubject.mccCodeTwo"
              :placeholder="'请先选择行业主体'"
              @change="changeMccCodeTwo"
              :api="apiSource.businessPage"
              :searchFlag="false"
              :queryParams="qualificationParams"
              :initParams="qualificationInitParams"
              value-field="categoryCode"
              label-field="categoryName"
            />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="24">
          <a-form-item label="费率:" :name="['jSubject', 'rate']" help="0.38~0.6 之间（小数点后两位，可取0.38%及0.6%）">
            <a-input v-model:value="jSubject.rate" disabled placeholder="请输入费率" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="企业特殊资质图片:" :name="['jSubject', 'specialQualifications']" help="根据商家类目判断是否需要资质，若需要则必选">
            <a-upload
              v-model:file-list="jSubject.specialQualifications"
              :max-count="1"
              name="specialQualifications"
              :custom-request="(file) => uploadFunc(file, 'jSubject.specialQualifications')"
              :accept="limitUpload.fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'specialQualifications')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="签约且授权标识:" name="signAndAuth">
            <a-switch v-model:checked="jSubject.signAndAuth" :unCheckedValue="0" :checkedValue="1" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="24">
          <a-form-item label="营业执照号码:" :name="['jSubject', 'businessLicenseNo']">
            <a-input v-model:value="jSubject.businessLicenseNo" placeholder="请输入营业执照号码" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="24" v-if="formData.apiType == '1'">
          <a-form-item label="营业执照法人手机号:" :name="['jSubject', 'businessLicenseMobile']" help="上传非经营者本人（签约账号）的营业执照时必填">
            <a-input v-model:value="jSubject.businessLicenseMobile" placeholder="请输入营业执照法人手机号" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业期限是否长期有效:" :name="['jSubject', 'longTerm']">
            <div>
              <a-switch v-model:checked="jSubject.longTerm" checked-children="是" un-checked-children="否" :unCheckedValue="0" :checkedValue="1" />
            </div>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业期限:" :name="['jSubject', 'dateLimitation']">
            <a-date-picker
              class="w-full"
              v-model:value="jSubject.dateLimitation"
              :valueFormat="'YYYY-MM-DD'"
              :disabled-date="(dataVal) => dataVal && data.cardPeriodBegin && dataVal <= new Date(formData.cardPeriodBegin).getTime()"
            />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="6">
          <a-form-item label="营业执照图片:" :name="['jSubject', 'businessLicensePic']">
            <a-upload
              v-model:file-list="jSubject.businessLicensePic"
              name="businessLicensePic"
              :max-count="1"
              :custom-request="(file) => uploadFunc(file, 'jSubject.businessLicensePic')"
              :accept="limitUpload.fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'businessLicensePic')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="6">
          <a-form-item
            label="营业执照授权函:"
            :name="['jSubject', 'businessLicenseAuthPic']"
            help="个体工商户如果使用总公司或其他公司的营业执照认证需上传该授权函图片"
          >
            <a-upload
              v-model:file-list="jSubject.businessLicenseAuthPic"
              name="businessLicenseAuthPic"
              :max-count="1"
              :custom-request="(file) => uploadFunc(file, 'businessLicenseAuthPic')"
              :accept="limitUpload.fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'businessLicenseAuthPic')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <template v-for="(item, index) in jSceneList" :key="item?.sceneType">
          <template v-if="item?.sceneType == 0 && formData.apiType == '1'">
            <a-col class="gutter-row" :span="24">
              <a-form-item label="店铺名称:" :name="['jSceneList', index, 'name']">
                <a-input v-model:value="item.name" placeholder="请输入店铺名称" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item label="店铺地址:" :name="['jSceneList', index, 'shopAddress1']">
                <areaCascader @change="(val) => changeArea(val, item)" v-model:value="item.shopAddress1" :getMultiple="true" width="100%" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item label="详细地址:" :name="['jSceneList', index, 'url']">
                <a-input v-model:value="item.url" placeholder="请输入详细地址" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="6">
              <a-form-item label="店铺内景图片" :name="['jSceneList', index, 'productUrl']">
                <a-upload
                  v-model:file-list="item.productUrl"
                  name="productUrl"
                  :max-count="1"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.productUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'productUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="6">
              <a-form-item label="店铺门头照图片:" :name="['jSceneList', index, 'indexUrl']">
                <a-upload
                  v-model:file-list="item.indexUrl"
                  name="indexUrl"
                  :max-count="1"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.indexUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'indexUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
            </a-col>
          </template>
        </template>
      </a-row>
      <a-row :gutter="16" v-if="formData.apiType == '0'">
        <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-400' }">其他信息</group-title>
        <a-col class="gutter-row" :span="24">
          <a-form-item label="交易场景:" name="sceneTypeArr">
            <a-checkbox-group v-model:value="formData.sceneTypeArr" :options="scenesOptions" @change="handleSceneTypeArr" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12" v-for="(item, index) in jSceneList" :key="item?.sceneType">
          <a-card size="small" :title="`${selectDictLabel(SCENES_TYPE_ALI, item?.sceneType)}场景`" class="w-full m-b-3">
            <!-- 线下 -->
            <div v-if="item?.sceneType == 0">
              <a-form-item label="店铺名称:" :name="['jSceneList', index, 'name']">
                <a-input v-model:value="item.name" placeholder="请输入店铺名称" />
              </a-form-item>
              <a-form-item label="店铺地址:" :name="['jSceneList', index, 'shopAddress1']">
                <areaCascader @change="(val) => changeArea(val, item)" v-model:value="item.shopAddress1" :getMultiple="true" width="100%" />
              </a-form-item>
              <a-form-item label="详细地址:" :name="['jSceneList', index, 'url']">
                <a-input v-model:value="item.url" placeholder="请输入详细地址" />
              </a-form-item>
              <a-form-item label="店铺内景图片" :name="['jSceneList', index, 'productUrl']">
                <a-upload
                  v-model:file-list="item.productUrl"
                  name="productUrl"
                  :max-count="1"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.productUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'productUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="店铺门头照图片:" :name="['jSceneList', index, 'indexUrl']">
                <a-upload
                  v-model:file-list="item.indexUrl"
                  name="indexUrl"
                  :max-count="1"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.indexUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'indexUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
            </div>
            <!-- 小程序 -->
            <div v-if="item?.sceneType == 2">
              <a-form-item label="小程序ID:" :name="['jSceneList', index, 'appid']">
                <a-input v-model:value="item.appid" placeholder="请输入小程序ID" />
              </a-form-item>
              <a-form-item label="小程序名称:" :name="['jSceneList', index, 'name']">
                <a-input v-model:value="item.name" placeholder="请输入小程序名称" />
              </a-form-item>
              <a-form-item label="小程序截图:" :name="['jSceneList', index, 'indexUrl']">
                <a-upload
                  v-model:file-list="item.indexUrl"
                  :max-count="1"
                  name="indexUrl"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.indexUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'indexUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
            </div>
            <!-- pc -->
            <div v-if="item?.sceneType == 3">
              <a-form-item label="网站名称:" :name="['jSceneList', index, 'name']">
                <a-input v-model:value="item.name" placeholder="请输入小程序名称" />
              </a-form-item>
              <a-form-item label="网站状态:" :name="['jSceneList', index, 'appStatus']">
                <a-radio-group v-model:value="item.appStatus" name="radioGroup" :options="DEV_TYPE" />
              </a-form-item>
              <a-form-item label="网站地址:" :name="['jSceneList', index, 'url']">
                <a-input v-model:value="item.url" placeholder="请输入网站地址" />
              </a-form-item>
              <a-form-item label="可登录此网站的测试账户:" :name="['jSceneList', index, 'demoAccount']">
                <a-input v-model:value="item.demoAccount" placeholder="请输入可登录此网站的测试账户" />
              </a-form-item>
              <a-form-item label="可以登录此网站的账户的密码:" :name="['jSceneList', index, 'demoPass']">
                <a-input v-model:value="item.demoPass" placeholder="请输入可以登录此网站的账户的密码" />
              </a-form-item>
              <a-form-item label="接入网址授权函:" :name="['jSceneList', index, 'authorizationUrl']">
                <a-upload
                  v-model:file-list="item.authorizationUrl"
                  :max-count="1"
                  name="authorizationUrl"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.authorizationUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'authorizationUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="网站首页截图:" :name="['jSceneList', index, 'indexUrl']">
                <a-upload
                  v-model:file-list="item.indexUrl"
                  :max-count="1"
                  name="indexUrl"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.indexUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'indexUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="网站商品页截图:" :name="['jSceneList', index, 'productUrl']">
                <a-upload
                  v-model:file-list="item.productUrl"
                  :max-count="1"
                  name="productUrl"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.productUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'productUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="网站支付页截图:" :name="['jSceneList', index, 'payUrl']">
                <a-upload
                  v-model:file-list="item.payUrl"
                  :max-count="1"
                  name="payUrl"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.payUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'payUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
            </div>
            <!-- app -->
            <div v-if="item?.sceneType == 4">
              <a-form-item label="应用状态:" :name="['jSceneList', index, 'appStatus']">
                <a-radio-group v-model:value="item.appStatus" name="radioGroup" :options="DEV_TYPE" />
              </a-form-item>
              <a-form-item label="应用名称:" :name="['jSceneList', index, 'name']">
                <a-input v-model:value="item.name" placeholder="请输入应用名称" />
              </a-form-item>
              <a-form-item label="投放市场应用:" :name="['jSceneList', index, 'appMarket']">
                <a-radio-group v-model:value="item.appMarket" :options="APP_MARKET" />
              </a-form-item>
              <a-form-item label="可登录此应用的测试账户:" :name="['jSceneList', index, 'demoAccount']">
                <a-input v-model:value="item.demoAccount" placeholder="请输入可登录此应用的测试账户" />
              </a-form-item>
              <a-form-item label="可以登录此应用的账户的密码:" :name="['jSceneList', index, 'demoPass']">
                <a-input v-model:value="item.demoPass" placeholder="请输入可以登录此应用的账户的密码" />
              </a-form-item>
              <a-form-item label="应用下载链接:" :name="['jSceneList', index, 'url']">
                <a-input v-model:value="item.url" placeholder="请输入应用下载链接" />
              </a-form-item>
              <a-form-item label="应用首页截图:" :name="['jSceneList', index, 'indexUrl']">
                <a-upload
                  v-model:file-list="item.indexUrl"
                  :max-count="1"
                  name="indexUrl"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.indexUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'indexUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="应用内支付页截图:" :name="['jSceneList', index, 'payUrl']">
                <a-upload
                  v-model:file-list="item.payUrl"
                  :max-count="1"
                  name="payUrl"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.payUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'payUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="商品或服务页截图:" :name="['jSceneList', index, 'productUrl']">
                <a-upload
                  v-model:file-list="item.productUrl"
                  :max-count="1"
                  name="productUrl"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.productUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'productUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="APP授权函图片:" :name="['jSceneList', index, 'authorizationUrl']">
                <a-upload
                  v-model:file-list="item.authorizationUrl"
                  :max-count="1"
                  name="authorizationUrl"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.authorizationUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'authorizationUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
            </div>
            <!-- 移动h5 -->
            <div v-if="item?.sceneType == 6">
              <a-form-item label="H5网站状态:" :name="['jSceneList', index, 'appStatus']">
                <a-radio-group v-model:value="item.appStatus" name="radioGroup" :options="DEV_TYPE" />
              </a-form-item>
              <a-form-item label="网站地址:" :name="['jSceneList', index, 'url']">
                <a-input v-model:value="item.url" placeholder="请输入网站地址" />
              </a-form-item>
              <a-form-item label="网站备注图片:" :name="['jSceneList', index, 'remarkUrl']">
                <a-upload
                  v-model:file-list="item.remarkUrl"
                  :max-count="1"
                  name="remarkUrl"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.remarkUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'remarkUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="H5网站首页截图:" :name="['jSceneList', index, 'indexUrl']">
                <a-upload
                  v-model:file-list="item.indexUrl"
                  :max-count="1"
                  name="indexUrl"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.indexUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'indexUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="H5网站支付页截图:" :name="['jSceneList', index, 'payUrl']">
                <a-upload
                  v-model:file-list="item.payUrl"
                  :max-count="1"
                  name="payUrl"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.payUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'payUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="H5网站授权函:" :name="['jSceneList', index, 'authorizationUrl']">
                <a-upload
                  v-model:file-list="item.authorizationUrl"
                  :max-count="1"
                  name="authorizationUrl"
                  :custom-request="(file) => uploadFunc(file, `jSceneList.${index}.authorizationUrl`)"
                  :accept="limitUpload.fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'authorizationUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
            </div>
            <p>请上传图片信息，最小5KB ， 最大5M（暂不限制图片宽高）， 图片格式必须为：png、bmp、gif、jpg、jpeg</p>
          </a-card>
        </a-col>
      </a-row>
    </a-form>
    <template #footer>
      <div v-if="props.formType != 'view'">
        <a-button @click="handleCancel"> 取消 </a-button>
        <a-button @click="getHistoryData"> 调用进件资料 </a-button>
        <a-button @click="handleSave"> 保存 </a-button>
        <a-button type="primary" @click="handleOk"> 提交 </a-button>
      </div>
    </template>
  </a-modal>
</template>
<script setup name="AlipayForm">
  import { computed, onMounted, reactive, ref, watch, toRefs } from 'vue'
  import { message, Upload } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import areaCascader from '/@/components/business/b-operation/area-cascader/index.vue'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { registApi } from '/@/api/business/b-operation/regist/index.js'
  import { registApi as agentRegistApi } from '/@/api/business/b-agent/regist/index.js'
  import { businessApi } from '/@/api/business/b-operation/regist/business.js'
  import { businessApi as agentBusinessApi } from '/@/api/business/b-agent/regist/business.js'
  import { wechatIndustryApi } from '/@/api/business/b-merchant/regist/wechat-industry-api.js'
  import { isUndefined, cloneDeep, isEmpty } from 'lodash'
  import { convertPathsToFiles, getSelectedOptions, getObjValue, setObjValue, selectDictLabel, modifyFields, strToArr } from '/@/utils/common.js'
  import { myUpload } from '/@/utils/myUpload'
  import { isNum, validatePhoneNot } from '/@/utils/validate'
  import {
    SUBJECT_TYPE, // 主体类型
    SCENES_TYPE_ALI, //场景类型
    DEV_TYPE, //应用状态
    APP_MARKET, //应用市场
  } from '/@/constants/dict'

  import { useUserStore } from '/@/store/modules/system/user'
  const USER_TYPE = useUserStore().userType // 用户类型: 1-平台;2-代理;4-商户

  const apiSource = {
    businessPage: (data) => {
      if (USER_TYPE == '2') return agentBusinessApi.page(data)
      if (USER_TYPE == '1') return businessApi.page(data)
    },
    detailPage: (data) => {
      if (USER_TYPE == '2') return agentRegistApi.detailPage(data)
      if (USER_TYPE == '1') return registApi.detailPage(data)
    },
    findId: (data) => {
      if (USER_TYPE == '2') return agentRegistApi.findId(data)
      if (USER_TYPE == '1') return registApi.findId(data)
    },
    save: (data) => {
      if (USER_TYPE == '2') return agentRegistApi.save(data)
      if (USER_TYPE == '1') return registApi.save(data)
    },
    submit: (data) => {
      if (USER_TYPE == '2') return agentRegistApi.submit(data)
      if (USER_TYPE == '1') return registApi.submit(data)
    },
    findIdByChannelType: (data) => {
      if (USER_TYPE == '2') return agentRegistApi.findIdByChannelType(data)
      if (USER_TYPE == '1') return registApi.findIdByChannelType(data)
    },
  }

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      default: () => {
        return {
          id: '', //商户进件详情id(mpdId)
          channelType: '',
          apiType: '', //产品类型
        }
      },
    },
    // 表单类型 add/update/view
    // add: 新增, update: 编辑,view: 查看
    formType: {
      type: String,
      default: 'add',
    },
    formOptions: {
      type: Object,
      default: () => {
        return {
          layout: 'vertical',
          name: 'basic',
          autocomplete: 'off',
        }
      },
    },
    params: {
      type: Object,
      default: () => {
        return {}
      },
    },
  })

  const emit = defineEmits(['update:open', 'ok'])
  const openForm = computed({ get: () => props.open, set: (val) => emit('update:open', val) })

  const alipayType = {
    0: '通用',
    1: '当面付',
  }

  // 图片字段
  const imgField = [
    'specialQualifications',
    'qualifications',
    'businessLicensePic',
    'financeLicensePics',
    'businessLicenseAuthPic',
    'indexUrl',
    'remarkUrl',
    'payUrl',
    'authorizationUrl',
    'productUrl',
    'idDocCopy',
    'idDocCopyBack',
    'authorizeLetterCopy',
    'businessAuthorizationLetter',
    'legalPersonCommitment',
    'legalPersonVideo',
    'businessAdditionPics',
  ]
  // 场景子表字段
  const jSceneListChild = {
    appMarket: undefined, //投放应用市场 0苹果 1应用宝 2华为 3 360 4小米 5豌豆夹 6其他
    merchantShortName: undefined, //商户简称
    servicePhone: undefined, //客服电话
    demoAccount: undefined, //测试用户
    type: undefined, //平台类型 0支付宝 1微信
    appStatus: undefined, //应用状态 0未上线 1已上线
    url: undefined, //网站地址/门店详细地址/应用下载链接
    sId: undefined, //商户经营信息表编号
    merchantId: undefined, //商户编号
    sceneType: undefined, //场景类型 0线下 1服务号和公众号 2小程序 3pc 4app 5企业微信 6移动h5
    productUrlM: undefined, //商品 商品服务/网站商品页/店铺内景
    appid: undefined, //商户appID/企微corpId
    name: undefined, //小程序名称/应用名称/门店名称/网站名称
    shopCityCode: undefined, //市
    demoPass: undefined, //测试密码
    shopDistrictCode: undefined, //区县
    id: undefined, //编号
    shopProvinceCode: undefined, //省份
    shopAddress1: [], //合并地址
    indexUrl: [], //首页 小程序/h5网站/应用首页/门店门头/服务或公众号页面
    remarkUrl: [], //备注
    payUrl: [], //支付 h5网站/应用支付页/网站支付页/企微页面
    authorizationUrl: [], //授权 h5网站授权/app授权/接入网址授权
    productUrl: [], //商品 商品服务/网站商品页
  }
  const initData = {
    mpdId: undefined, //商户进件关联编号
    jBankAccounts: {}, //结算银行账户表
    jSubject: {
      financeInstitution: undefined, //是否为金融机构 0否1是
      businessLicenseMobile: undefined, //营业执照法人手机号
      merchantShortName: undefined, //商户简称
      dateLimitation: undefined, //营业期限
      settlementId: undefined, //结算规则ID
      subjectType: undefined, //主体类型： 0: 营业执照上的主体类型一般为个体户、个体工商户、个体经营 1: 营业执照上的主体类型一般为有限公司、有限责任公司 2: 包括各级、各类政府机关，如机关党委、税务、民政、人社、工商、商务、市监等 3:包括国内各级、各类政府机构、事业单位等。 如：公安、党团、司法、交通、旅游、工商税务、市政、医疗、教育、学校等机构 4: 包括社会团体、民办非企业、基金会、基层群众性自治组织、农村集体经济组织等组织
      mccCode: undefined, //经营类目
      mccCodeOne: undefined, //经营类目
      mccCodeTwo: undefined, //经营类目
      activitiesAdditions: undefined, //活动附加说明 用,拼接
      qualificationType: undefined, //所属行业类型
      qualifications: [], //特殊资质说明 用,拼接
      signAndAuth: 1, //签约且授权标识，默认为false，只进行签约操作； 如果设置为true，则表示签约成功后，会自动进行应用授权操作。
      longTerm: 1, //营业执照是否长期有效 0否 1是
      activitiesId: undefined, //活动ID
      merchantId: undefined, //自定义商户编号
      rate: undefined, //服务费率（%），0.38~0.6 之间（小数点后两位，可取0.38%及0.6%）。 当签约且授权标识 sign_and_auth=true 时，该费率信息必填
      activitiesRate: undefined, //活动费率
      legalPersonVideo: undefined, //法人开户意愿视频 1、建议法人按如下话术录制“法人开户意愿视频”： 我是#公司全称#的法定代表人（或负责人），特此证明本公司申请的商户号为我司真实意愿开立且用于XX业务（或XX服务）。我司现有业务符合法律法规及腾讯的相关规定。 2、支持上传20M内的视频，格式可为avi、wmv、mpeg、mp4、mov、mkv、flv、f4v、m4v、rmvb； 3、请填写通过视频上传API预先上传视频生成好的MediaID 。
      id: undefined, //编号
      debitActivitiesRate: undefined, //借记卡活动费率
      creditActivitiesRate: undefined, //信用卡活动费率
      legalPersonCommitment: undefined, //法人开户承诺函1、请上传法定代表人或负责人亲笔签署的开户承诺函扫描件（下载模板）。亲笔签名承诺函内容清晰可见，不得有涂污，破损，字迹不清晰现象； 2、请填写通过图片上传API预先上传图片生成好的MediaID
      email: undefined, //邮箱
      specialLicenseType: undefined, //特殊资质类型
      certificateLetterCopy: undefined, //单位证明函照片
      businessLicenseAddress: undefined, //营业执照的注册地址，若该字段未填写，系统将会查询国家工商信息填入。需注意若工商信息查询不到，则会被审核驳回。
      servicePhone: undefined, //服务电话
      businessAdditionMsg: undefined, //补充说明
      businessLicenseName: undefined, //营业执照商户名称
      businessLicenseNo: undefined, //营业执照号码
      businessAdditionPics: undefined, //补充材料 1、最多可上传5张照片； 2、请填写通过图片上传API预先上传图片生成好的MediaID。
      phone: undefined, //手机号
      name: undefined, //姓名
      financeType: undefined, //金融机构类型 为金融机构时必传
      storeInfo: undefined, //销售场景
      account: undefined, //支付宝账号
      specialQualifications: [], //企业特殊资质图片
      businessLicensePic: [], //营业执照图片
      financeLicensePics: [], //金融机构许可证图片 用,拼接
      businessLicenseAuthPic: [], //营业执照授权函
    }, //商户经营信息表出参
    apiType: 1, //接口类型 0通用 1当面付
    jIdentitiesList: [], //商户身份信息
    jSceneList: [], //商户场景信息
    sceneTypeArr: [], //场景类型
  }
  const formData = reactive(cloneDeep(initData))
  const { jBankAccounts, jSubject, jSceneList, sceneTypeArr } = toRefs(formData)

  const rules = ref({
    sceneTypeArr: [{ required: true, message: '交易场景 不能为空!', trigger: ['blur', 'change'] }], //交易场景
    jSubject: {
      account: [{ required: true, message: '商户号/支付宝账号不能为空!' }],
      name: [{ required: true, message: '姓名不能为空!' }],
      phone: [
        { required: true, message: '手机号码不能为空!' },
        {
          validator: validatePhoneNot,
        },
      ],
      subjectType: [{ required: true, message: '主体类型 不能为空!', trigger: ['blur', 'change'] }],
      mccCodeOne: [{ required: true, message: '经营类目 不能为空!', trigger: ['blur', 'change'] }],
      mccCodeTwo: [{ required: true, message: '经营类目 不能为空!', trigger: ['blur', 'change'] }],
      specialQualifications: [
        {
          required: computed(() => {
            return jSubject.value.specialLicenseType == '1'
          }),
          message: '企业特殊资质图片 不能为空!',
          trigger: ['blur', 'change'],
        },
      ],
      businessLicenseNo: [{ required: true, message: '营业执照号码 不能为空!', trigger: ['blur', 'change'] }],
      businessLicenseMobile: [{ required: true, message: '营业执照法人手机号 不能为空!', trigger: ['blur', 'change'] }],
      longTerm: [{ required: true, message: '营业期限是否长期有效 不能为空!', trigger: ['blur', 'change'] }],
      businessLicensePic: [
        {
          required: computed(() => {
            return jSubject.value.subjectType == '0'
          }),
          message: '营业执照图片 不能为空!',
          trigger: ['blur', 'change'],
        },
      ],
    },
    jSceneList: computed(() => {
      let arr = []
      if (jSceneList.value && jSceneList.value.length > 0) {
        jSceneList.value.forEach((item, index) => {
          arr.push({
            appMarket: [{ required: true, message: '投放应用市场 不能为空!', trigger: ['blur', 'change'] }], //投放应用市场 0苹果 1应用宝 2华为 3 360 4小米 5豌豆夹 6其他
            merchantShortName: [{ required: true, message: '商户简称 不能为空!', trigger: ['blur', 'change'] }], //商户简称
            servicePhone: [{ required: true, message: '客服电话 不能为空!', trigger: ['blur', 'change'] }], //客服电话
            indexUrl: [{ required: true, message: '小程序/h5网站/应用首页/门店门头/服务或公众号页面 不能为空!', trigger: ['blur', 'change'] }], //首页 小程序/h5网站/应用首页/门店门头/服务或公众号页面
            payUrl: [{ required: true, message: 'h5网站/应用支付页/网站支付页/企微页面 不能为空!', trigger: ['blur', 'change'] }], //支付 h5网站/应用支付页/网站支付页/企微页面
            demoAccount: [{ required: false, message: '测试用户 不能为空!', trigger: ['blur', 'change'] }], //测试用户
            appStatus: [{ required: true, message: '应用状态 不能为空!', trigger: ['blur', 'change'] }], //应用状态 0未上线 1已上线
            url: [{ required: item.sceneType == '0', message: '网站地址/门店详细地址/应用下载链接 不能为空!', trigger: ['blur', 'change'] }], //网站地址/门店详细地址/应用下载链接
            sId: [{ required: true, message: '商户经营信息表编号 不能为空!', trigger: ['blur', 'change'] }], //商户经营信息表编号
            authorizationUrl: [{ required: false, message: '授权 不能为空!', trigger: ['blur', 'change'] }], //授权 h5网站授权/app授权/接入网址授权
            merchantId: [{ required: true, message: '商户编号 不能为空!', trigger: ['blur', 'change'] }], //商户编号
            productUrlM: [{ required: true, message: '图片 不能为空!', trigger: ['blur', 'change'] }], //商品 商品服务/网站商品页/店铺内景
            appid: [{ required: true, message: 'appID 不能为空!', trigger: ['blur', 'change'] }], //商户appID/企微corpId
            name: [{ required: true, message: '名称 不能为空!', trigger: ['blur', 'change'] }], //小程序名称/应用名称/门店名称/网站名称
            demoPass: [{ required: false, message: '测试密码 不能为空!', trigger: ['blur', 'change'] }], //测试密码
            shopProvinceCode: [{ required: true, message: ' 不能为空!', trigger: ['blur', 'change'] }], //省份
            shopCityCode: [{ required: true, message: ' 不能为空!', trigger: ['blur', 'change'] }], //市
            shopDistrictCode: [{ required: true, message: ' 不能为空!', trigger: ['blur', 'change'] }], //区县
            shopAddress1: [{ required: true, message: '地址 不能为空!', trigger: ['blur', 'change'] }], //地址
            remarkUrl: [{ required: true, message: '备注 不能为空!', trigger: ['blur', 'change'] }], //备注
            id: [{ required: true, message: '编号 不能为空!', trigger: ['blur', 'change'] }], //编号
            productUrl: [{ required: true, message: '商品 不能为空!', trigger: ['blur', 'change'] }], //商品 商品服务/网站商品页
          })
        })
      }
      return arr
    }),
  })

  const formRef = ref()
  const limitUpload = {
    fileType: ['.jpg', '.jpeg', '.png', '.bmp', '.gif'],
    fileSize: 5,
  }
  const beforeUpload = (file, fileList, type) => {
    // 校检文件类型
    if (limitUpload.fileType.length) {
      const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      const isTypeOk = limitUpload.fileType.includes(fileExt)
      if (!isTypeOk) {
        message.warning(`文件格式不正确, 请上传${limitUpload.fileType.toString().replace(/\./g, '').replace(/,/g, '、')}格式文件!`)
        return false || Upload.LIST_IGNORE
      }
    }

    // 校检文件大小
    if (limitUpload.fileSize) {
      const isLt = file.size / 1024 / 1024 < limitUpload.fileSize
      if (!isLt) {
        message.warning(`上传文件大小不能超过 ${limitUpload.fileSize} MB!`)
        return false || Upload.LIST_IGNORE
      }
    }

    return true
  }

  // 上传文件自定义的方法
  const uploadFunc = async (file, fieldName) => {
    // console.log('file==>', file)
    // 确保获取到文件对象
    const fileObj = file.file
    if (!fileObj) {
      return
    }
    const response = await myUpload(file)
    console.log('response==>', response)
    let arr = getObjValue(formData, fieldName).map((item) => {
      if (item.uid === fileObj.uid) {
        message.success(`${fileObj.name} 上传成功`)
        return response
      }
      return item
    })
    setObjValue(formData, fieldName, arr)
  }

  //校验表单
  const validateForm = async () => {
    let isValid = false
    try {
      await formRef.value.validate()
      isValid = true
    } catch (error) {
      message.warning(error.errorFields[0].errors)
      isValid = false
    }
    return isValid
  }

  //保存
  const handleSave = async () => {
    const param = { ...cloneDeep(formData), ...cloneDeep(props.params) }
    imgInit(param)
    if (props.formType != 'view') {
      try {
        let res = await apiSource.save(param)
        message.success('保存成功')
        emit('ok', formData)
        return res
      } catch (error) {
        console.error(error)
      }
    }
  }

  //提交
  const handleOk = () => {
    // open.value = false
    validateForm().then((isValid) => {
      if (isValid) {
        handleSave().then(() => {
          const param = { checkStatus: 0, id: props.rowData.id }
          apiSource.submit(param).then(() => {
            message.success('提交成功')
            resetForm()
            emit('ok', formData)
            openForm.value = false
          })
        })
      }
    })
  }

  const handleCancel = () => {
    openForm.value = false
    resetForm()
    // open.value = false
  }
  const resetForm = () => {
    // 重置表单的 UI 状态
    try {
      formRef.value.resetFields()
    } catch (error) {
      console.error(error)
    }
    // 重置表单数据
    Object.assign(formData, cloneDeep(initData))
  }

  let areaFieldArr = ['shopProvinceCode', 'shopCityCode', 'shopDistrictCode']
  // 地址拆分
  const changeArea = (val, data) => {
    val.forEach((item, index) => {
      data[areaFieldArr[index]] = item
    })
  }
  // 地址合并
  function mergeArea(data) {
    data.jSceneList.forEach((item) => {
      if (item.sceneType == '0') {
        for (let i = 0; i <= areaFieldArr.length; i++) {
          if (!item[areaFieldArr[i]]) {
            item.shopAddress1 = item[areaFieldArr[i - 1]]
          }
        }
      }
    })
  }

  //调用进件资料
  function getHistoryData() {
    SmartLoading.show()
    let p = { id: props.rowData.id, channelType: props.rowData.channelType }
    apiSource
      .findIdByChannelType(p)
      .then((res) => {
        // jSubject/jSceneList
        if (isEmpty(res?.data)) return
        let resData = res.data
        imgInit(resData)
        mergeArea(resData)
        Object.assign(formData, resData)
        getSceneTypeArr()
        initFormList()
      })
      .finally(() => {
        SmartLoading.hide()
      })
  }
  // 获取表单数据
  function getFormData(data) {
    SmartLoading.show()
    let p = { mpdId: data.id, type: data.channelType }
    apiSource
      .findId(p)
      .then((res) => {
        // jSubject/jSceneList
        let resData = res.data
        resData.mpdId = data.id
        imgInit(resData)
        mergeArea(resData)
        Object.assign(formData, resData)
        if (resData.apiType == 1 && !resData.jSceneList.some((item) => item.sceneType == 0)) {
          // 当面付线下场景处理
          initFormList()
        }
        getSceneTypeArr()
      })
      .catch((err) => {
        console.error(err)
        initFormList()
      })
      .finally(() => {
        SmartLoading.hide()
      })
  }
  // 图片初始化
  function imgInit(resData) {
    modifyFields(resData, imgField, (value, key) => {
      let val
      if (isEmpty(value)) return
      if (typeof value === 'string') {
        val = strToArr(value).map((item, index) => {
          return {
            uid: `db-file-${index}`,
            name: `${key}${index > 0 ? '_' + index : ''}`,
            status: 'done',
            url: item,
          }
        })
      }
      if (Array.isArray(value)) {
        val = value.map((e) => e.url).toString()
      }
      return val
    })
  }

  // 获取场景列表--场景初始化
  function getSceneTypeArr() {
    if (!isEmpty(jSceneList.value) && jSceneList.value.length > 0) {
      sceneTypeArr.value = [...new Set(jSceneList.value.map((item) => item.sceneType))]
    }
  }

  // 获取场景类型
  const handleSceneTypeArr = (val) => {
    sceneChange()
  }
  const sceneChange = () => {
    let sceneArr = jSceneList.value.map((item) => item?.sceneType)
    // formData.jSceneList.push({ ...cloneDeep(jSceneListChild), sceneType: 0 })
    formData.sceneTypeArr.forEach((item) => {
      if (!sceneArr.includes(item)) {
        formData.jSceneList.push({ ...cloneDeep(jSceneListChild), sceneType: item, type: props.rowData?.channelType })
      }
    })
    sceneArr.forEach((item, index) => {
      if (!formData.sceneTypeArr.includes(item)) {
        jSceneList.value.splice(index, 1)
      }
    })
  }

  // 主体类型
  const headParams = computed(() => {
    return {
      pCategoryCode: '000000',
    }
  })
  const headInitParams = computed(() => {
    return {
      categoryCode: jSubject.value.mccCodeOne,
    }
  })
  const qualificationParams = computed(() => {
    return {
      pCategoryCode: jSubject.value.mccCodeOne ? jSubject.value.mccCodeOne : 'unknown',
    }
  })
  const qualificationInitParams = computed(() => {
    return {
      categoryCode: jSubject.value.mccCodeTwo,
    }
  })
  // 切换行业一级类目
  const changeMccCodeOne = (val) => {
    jSubject.value.mccCodeTwo = undefined
  }
  // 切换行业二级类目
  const changeMccCodeTwo = (...val) => {
    console.log('二级类目==>', val)
    jSubject.value.rate = val[1][0].rate
    jSubject.value.specialLicenseType = val[1][0].qualificationsType // 是否上传特殊资质
  }

  function show(data) {
    if (data && !isEmpty(data)) {
      // Object.assign(formData, data)
      getFormData(data)
    }
    console.log('show==>', data)
  }

  /* 必填场景 */
  const requiredScene = computed(() => {
    return []
  })
  const scenesOptions = computed(() => {
    return SCENES_TYPE_ALI.map((item) => {
      return {
        ...item,
        disabled: requiredScene.value.includes(item.value),
        label: item.label,
        value: item.value,
      }
    })
  })

  /* 数组表单初始化 */
  function initFormList() {
    // 必填场景处理
    // requiredScene.value.forEach((item) => {
    //   if (formData.jSceneList.some((item) => item.sceneType == item)) return
    //   formData.jSceneList.push({ ...cloneDeep(jSceneListChild), sceneType: item, type: props.rowData?.channelType })
    // })
    if (formData.jSceneList.some((item) => item.sceneType == 0)) return
    formData.jSceneList.push({ ...cloneDeep(jSceneListChild), sceneType: 0, type: props.rowData?.channelType })
    getSceneTypeArr()
  }
  watch(
    [() => props.rowData, () => props.open, () => props.params],
    (newVal) => {
      // apiType 判断通用还是当面付
      formData.apiType = props.params?.apiType || props.rowData?.apiType
      if (props.rowData?.id) {
        formData.mpdId = props.rowData?.id
      }
      if ((props.formType == 'update' || props.formType == 'view') && props.open) {
        show(cloneDeep(newVal[0]))
      }
      if (props.formType == 'add' && props.open) {
        initFormList()
      }
    },
    { deep: true, immediate: true },
  )
  // watch([() => formData.sceneTypeArr], (newVal) => {}, { deep: true, immediate: true })
  // 在组件挂载时初始化地址选项
  onMounted(() => {})
  defineExpose({
    formRef,
  })
</script>
<style lang="scss" scoped></style>
